﻿//#define OverloadDelete
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class VotesController : Controller
    {
        private BaseDBContext db = new BaseDBContext();

        // GET: /Votes/Details/5

        public ActionResult Like(int id = 0)
        {
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");

            Recipe recipe = db.Recipes.Find(id);
            int user = (int)Session["LoggedId"];

            IQueryable<Vote> a = db.Votes.Where(m => m.RecipeID == id && m.UserID == user);

            if (a.Count() == 0)
            {
                Vote v = new Vote();
                v.UserID = user;
                v.RecipeID = id;
                v.Like = true;
                db.Votes.Add(v);
                db.SaveChanges();
            }
            else
            {
                Vote b = a.First();
                if (b.Like == false)
                {
                    b.Like = true;
                }
                db.SaveChanges();
            }

            return RedirectToAction("Details/" + id, "Recipes");
        }

        public ActionResult DontLike(int id = 0)
        {
            if (Session["LoggedId"] == null)
                return RedirectToAction("Error", "Home");

            Recipe recipe = db.Recipes.Find(id);
            int user = (int)Session["LoggedId"];

            IQueryable<Vote> a = db.Votes.Where(m => m.RecipeID == id && m.UserID == user);

            if (a.Count() == 0)
            {
                Vote v = new Vote();
                v.UserID = user;
                v.RecipeID = id;
                v.Like = false;
                db.Votes.Add(v);
                db.SaveChanges();
            }
            else
            {
                Vote b = a.First();
                if (b.Like == true)
                {
                    b.Like = false;
                }
                db.SaveChanges();
            }

            return RedirectToAction("Details/" + id, "Recipes");
        }
    }
}